<template>
  <div class="app-container">
    <el-card>
      <!-- 搜索模块 -->
      <el-form v-show="showSearch" ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
        <el-form-item label="费用类型" prop="scene">
          <el-select v-model="queryParams.type" placeholder="字典类型" style="width: 240px" @change="getList">
            <el-option v-for="dict in costOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <!-- 图标权限模块 -->
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button v-hasPermi="['admin:region:form:add:post']" type="primary" plain icon="el-icon-date" size="mini"
                     @click="handleAdd">新增费用
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button v-hasPermi="['admin:region:form:delete:{id}:delete']" type="danger" plain icon="el-icon-delete"
                     size="mini" :disabled="multiple" @click="handleDelete">批量删除
          </el-button>
        </el-col>
<!--        <right-toolbar :show-search.sync="showSearch" @queryTable="getList" />-->
      </el-row>
    </el-card>
    <el-card style="margin-top: 20px">
      <!-- 展示模块 -->
      <el-table v-loading="loading" :data="costtypeList" @selection-change="handleSelectionChange" border>
        <el-table-column type="selection" width="100" align="center" />
        <el-table-column label="名称" prop="name" ></el-table-column>
        <el-table-column label="备注" prop="remark" width="100" />
        <el-table-column
          v-if="hasPermi(['admin:budget:form:edit:post', 'system:clearsavefile:download:post', 'admin:budget:form:delete:{id}:delete'])"
          label="操作" align="center" class-name="small-padding fixed-width" width="180">
          <template slot-scope="scope">
            <el-button v-hasPermi="['admin:budget:form:edit:post']" size="mini" type="text" icon="el-icon-edit"
                       @click="handleUpdate(scope.row)">修改</el-button>
            <el-button v-hasPermi="['admin:budget:form:delete:{id}:delete']" size="mini" type="text" icon="el-icon-delete"
                       @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                  @pagination="getList" />
    </el-card>


    <!-- 文件上传|修改 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="costtypeForm" :model="costtypeForm" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="costtypeForm.name" placeholder="名称" style="width: 240px" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="costtypeForm.type" placeholder="类型" size="small" style="width: 240px">
            <el-option v-for="dict in costOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="remark">
          <el-input v-model="costtypeForm.remark" placeholder="描述"  style="width: 240px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { listCostType, addCostType, delCostType,editCostType  } from "@/api/vadmin/budget/cost/costapi";
import { getToken } from "@/utils/auth";
import { Decrypt } from "@/utils/AesHmacMD5";

export default {
  name: "dict",
  data() {
    return {
      // 遮罩层
      loading: true,costOptions:[{value:0,label:'钻测录合同'},{value:1,label:'钻井'},{value:2,label:'研究费及管理费'},{value:3,label:'试油'},{value:4,label:'其它'}],regionOptions:[],
      // 选中数组
      ids: [],
      valNames: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 模板表格数据
      costtypeList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 场景数据字典
      sceneOptions: [],
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,  // 当前页数
        pageSize: 10,  // 每页显示几个
        name: undefined,
        type: 3
      },
      // 表单参数
      costtypeForm: {
        id: undefined,
        name: undefined,
        type: undefined,
        remark: undefined
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
      },
      uploadData: {},
      headers: {
        Authorization: "Bearer " + getToken()
      },
    };
  },
  created() {
    // 初始化数字台账列表
    this.getList();
  },
  methods: {
    validatorPath() {
      return (rule, value, callback) => {
        if (this.form.id == undefined && !value) {
          return callback(new Error("模板文件不能为空"));
        } else {
          callback();
        }
      }
    },
    getList() {
      this.loading = true;
      listCostType(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        var resData = JSON.parse(Decrypt(response.data))
        this.costtypeList = resData.results;
        this.total = resData.count;
        this.loading = false;
      });
    },
    // 表单重置
    reset() {
      this.costtypeForm = {
        id: undefined,
        name: undefined,
        type: undefined,
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 文件上传按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增";
      //一级区域
      this.costtypeForm.id = '';
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.$refs.uploadRef.clearFiles()
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["costtypeForm"].validate(valid => {
        if (valid) {
          if (this, this.costtypeForm.id == undefined||this.costtypeForm.id == '') {
            addCostType(this.costtypeForm).then(response => {
              this.msgSuccess(response.msg);
              this.reset();
              this.open = false;
              this.getList();
            });
          } else {
            editCostType(this.costtypeForm).then(response => {
              this.msgSuccess(response.msg);
              this.reset();
              this.open = false;
              this.getList();
            })
          }
        }
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.valNames = selection.map(item => item.formCode);
      this.single = selection.length !== 1;
      this.multiple = selection.length < 2;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      var ids=[],_this=this
      if(row.id!=undefined){
        ids = [row.id]
      }else{
         ids = this.ids;
      }
      const names = row.name || this.valNames
      this.$confirm('是否确认删除编码为"' + names + '"的数据项? 请谨慎操作！', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delCostType({id:ids});

      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      });
    },
    // 场景字典翻译
    sceneFormat(row, column) {
      return this.selectDictLabel(this.sceneOptions, row.scene);
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.costtypeForm = row;
      this.open = true;
      this.title = "修改";
    },
    /** 文件上传成功调用的钩子函数 */
    handleSuccess(data) {
      inspectHeaderAll({ 'path': data.saveFile }).then(response => {
        var resData = JSON.parse(Decrypt(response.data))
        if (resData.bol) {
          this.form.path = data.saveFile
          this.$message.success('文件上传成功！');
          this.$refs.uploadRef.clearFiles()
        } else {
          this.onInspect(resData.repeat_values)
        }
      })

    },
    /** 文件上传失败调用的钩子函数 */
    onError() {
      this.form.path = undefined
      this.$message.error('文件上传失败！');
      this.$refs.uploadRef.clearFiles()
    },
    /** 重复列回显函数 */
    onInspect(data) {
      this.form.path = undefined
      this.$message.error('文件' + data + '列重复，请检查之后重新上传！');
      this.$refs.uploadRef.clearFiles()
    }
  }
};
</script>
